import enum

from pydantic import BaseModel, Field, root_validator


class LoginTypeEnum(enum.IntEnum):
    USERNAME_WITH_PASSWORD = 0
    EMAIL_WITH_PASSWORD = 1
    EMAIL_WITH_VERIFY_CODE = 2
    PHONE_WITH_PASSWORD = 3
    PHONE_WITH_VERIFY_CODE = 4


class TenantUserLoginModel(BaseModel):

    username: str = Field(None, description="用户名", max_length=255)
    email: str = Field(None, description="邮箱", max_length=64)
    phone: str = Field(None, description="手机号", max_length=32)
    password: str = Field(None, description="密码", max_length=16)
    verify_code: str = Field(None, description="验证码", max_length=6)
    login_type: LoginTypeEnum = Field(..., description="登陆方式")

    @root_validator()
    def validate_root(cls, attrs):
        login_type = attrs.get("login_type")
        if login_type == LoginTypeEnum.USERNAME_WITH_PASSWORD:
            raise ValueError("不支持的登陆方式")
            # res = cls.verify_params(attrs, "username", "password")
        elif login_type == LoginTypeEnum.EMAIL_WITH_PASSWORD:
            res = cls.verify_params(attrs, "email", "password")
        elif login_type == LoginTypeEnum.EMAIL_WITH_VERIFY_CODE:
            res = cls.verify_params(attrs, "email", "verify_code")
        elif login_type == LoginTypeEnum.PHONE_WITH_PASSWORD:
            res = cls.verify_params(attrs, "phone", "password")
        elif login_type == LoginTypeEnum.PHONE_WITH_VERIFY_CODE:
            res = cls.verify_params(attrs, "phone", "verify_code")
        else:
            raise ValueError("不支持的登陆方式")
        res["login_type"] = login_type
        return res

    @classmethod
    def verify_params(cls, attrs, key1, key2):
        value1 = attrs.get(key1)
        value2 = attrs.get(key2)
        if not value1 or not value2:
            raise ValueError("缺失参数")
        return {key1:value1, key2:value2}


class TenantUserRegisterModel(BaseModel):
    email: str = Field(..., description="邮箱", max_length=64, regex=r"(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)")
    username: str = Field(None, description="用户名", max_length=255)
    first_name: str = Field(None, description="姓", max_length=64)
    last_name: str = Field(None, description="名", max_length=64)
    alias: str = Field(None, description="别名", max_length=32)
    avatar: str = Field(None, description="头像", max_length=255)
    password: str = Field(..., description="密码", max_length=16)
    re_password: str = Field(..., description="密码", max_length=16)

    @root_validator()
    def validate_root(cls, attrs: dict):
        password = attrs.get("password")
        re_password = attrs.get("re_password")
        if password != re_password:
            raise ValueError("两次密码不一致")
        attrs.pop("re_password", None)
        return attrs


if __name__ == '__main__':
    TenantUserLoginModel(username="das", phone="1234", password="12d3", verify_code="123455", login_type=0)


